<?php

namespace App\Models\Balance;

use App\Models\Manger\Manger;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class BalanceLog extends Model
{
    protected $table = 'custom_balance_log';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];


    public static function getList(Request $request, $cpid, $category)
    {
        $query = self::with(['salesmangerinfo' => function ($query) {
            $query->select(['id', 'realname', 'username']);
        }])->where(['cpid' => $cpid])->orderBy('create_at', 'desc');
        $query->where('category', $category);
        $archive_no = $request->archive_no;
        if ($archive_no != '') {
            $query->where('archive_no', 'like', '%' . $archive_no . '%');
        }

        $company_name = $request->company_name;
        if ($company_name != '') {
            $query->where('company_name', 'like', '%' . $company_name . '%');
        }

        $start_time = strtotime($request->start_time) > 0 ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = strtotime($request->end_time) > 0 ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > 0) {
            $query->where('create_at', '>=', $start_time)->where('create_at', '<=', $end_time);
        }

        $limit = $request->limit ?? 10;
        $list = $query->paginate($limit)->toArray();
        return paginateDataToArray($list);
    }


    public  function salesmangerinfo()
    {
        return $this->hasOne(Manger::class, 'id', 'sales_manger_id');
    }
}
